package com.fushenlan.epidemicControl.service.Impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fushenlan.Vo.EmergencyVO;
import com.fushenlan.commons.GeneralResponse;
import com.fushenlan.epidemicControl.dto.EmergencyDTO;
import com.fushenlan.epidemicControl.mapper.BuildingInfoMapper;
import com.fushenlan.epidemicControl.mapper.EmergencyMapper;
import com.fushenlan.epidemicControl.mapper.InhabitantInfoMapper;
import com.fushenlan.epidemicControl.service.EmergencyService;
import com.fushenlan.po.BuildingInfo;
import com.fushenlan.po.Emergency;
import com.fushenlan.po.InhabitantInfoDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author PC
 * @title: EmergencyServiceImpl
 * @projectName SpringBootDemo
 * @description: TODO
 * @date 2021/8/14 18:43
 */
@Service
@Slf4j
public class EmergencyServiceImpl extends ServiceImpl<EmergencyMapper, Emergency>implements EmergencyService {

    @Resource
    private EmergencyMapper emergencyMapper;

    @Resource
    private InhabitantInfoMapper inhabitantInfoMapper;
    @Resource
    private BuildingInfoMapper buildingInfoMapper;
    @Override
    public GeneralResponse commitEmergency(EmergencyDTO emergencyDTO) {

        Emergency emergency=new Emergency();
        BeanUtils.copyProperties(emergencyDTO,emergency);
        emergency.setState(1);
        emergency.setCreateTime(LocalDateTime.now());
        log.info("用户id找出小区id用户id为{}",emergency.getUserId());
        InhabitantInfoDO inhabitantInfoDO =inhabitantInfoMapper.selectById(emergency.getUserId());
        emergency.setBuildingInfoId(inhabitantInfoDO.getResidentialId());
        log.info("该小区id为{}",inhabitantInfoDO.getResidentialId());
        this.save(emergency);
        return GeneralResponse.success();
    }
    @Override
    public GeneralResponse<List<EmergencyDTO>> deal(String id, String result,String dealUserId) {
        Emergency emergency =emergencyMapper.selectById(id);
        emergency.setResult(result);
        emergency.setState(3);
        emergency.setDealTime(LocalDateTime.now());
        emergencyMapper.updateById(emergency);
        return GeneralResponse.success();
    }

    @Override
    public GeneralResponse<EmergencyVO> getInfoById(String ids) {
        Long id = Long.valueOf(ids);
        Emergency emergency=emergencyMapper.selectById(id);
        long userId = Long.parseLong(emergency.getUserId());
        InhabitantInfoDO inhabitantInfoDO=inhabitantInfoMapper.selectById(userId);
        EmergencyVO emergencyVO = new EmergencyVO();
        BeanUtils.copyProperties(emergency,emergencyVO);
        //根据用户id查出地址
        StringBuilder address=new StringBuilder();

        //小区
        String residential =buildingInfoMapper.selectById(inhabitantInfoDO.getResidentialId()).getName();
        //楼层
        String building =buildingInfoMapper.selectById(inhabitantInfoDO.getBuildingId()).getName();
        //房间号
        String house =buildingInfoMapper.selectById(inhabitantInfoDO.getHouseId()).getName();
        address.append(residential).append(building).append(house);

        emergencyVO.setAddress(address.toString());
        emergencyVO.setPhone(inhabitantInfoDO.getPhoneNumber());
        emergencyVO.setUserName(inhabitantInfoDO.getUserName());
        return GeneralResponse.success(emergencyVO);
    }

    @Override
    public GeneralResponse<List<EmergencyDTO>> getListByStateAndType(String state, String level,String neighborhoodId,String inhabitantId,String userName) {
        Map<String,String> parmMap=new HashMap<>();
        if(!"".equals(state)&&null!=state){
            parmMap.put("state",state);
        }
        if(!"".equals(level)&&null!=level){
            parmMap.put("level",level);
        }
        if(!"".equals(inhabitantId)&&null!=inhabitantId){
            parmMap.put("dealId",inhabitantId);
        }
        if(!"".equals(userName)&&null!=userName){
            parmMap.put("userName",userName);
        }
        List<Emergency> list=emergencyMapper.findAllEmergencyList(parmMap);
        List<EmergencyDTO> emergencyDTOList=new ArrayList<>();
        for(Emergency emergency :list){
            EmergencyDTO emergencyDTO = new EmergencyDTO();
            BeanUtils.copyProperties(emergency,emergencyDTO);
            InhabitantInfoDO inhabitantInfoDO=inhabitantInfoMapper.selectById(emergency.getUserId());
            if(inhabitantInfoDO!=null){
                emergencyDTO.setUserName(inhabitantInfoDO.getUserName());
            }else {
                emergencyDTO.setUserName("未知");
            }

            emergencyDTOList.add(emergencyDTO);
        }
        return GeneralResponse.success(emergencyDTOList);
    }

    @Override
    public GeneralResponse<List<EmergencyDTO>> getListByUserId(String userId) {

        List<Emergency> list = new LambdaQueryChainWrapper<Emergency>(emergencyMapper)
                .eq(Emergency::getUserId, userId).list();
        List<EmergencyDTO> emergencyDTOList=new ArrayList<>();
        for(Emergency emergency :list){
            EmergencyDTO emergencyDTO = new EmergencyDTO();
            BeanUtils.copyProperties(emergency,emergencyDTO);
            emergencyDTOList.add(emergencyDTO);
        }
        return GeneralResponse.success(emergencyDTOList);
    }

    @Override
    public  String upload( MultipartFile file,  String id){
        if(!file.isEmpty()){

            /**
             * #file.uploadFolder=/home/upload/
             * file.uploadFolder=d://upload/
             * C:\\uploadFile
             */
            String uploadPath = "/home/uploadFile";
            // 如果目录不存在则创建
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            String OriginalFilename = file.getOriginalFilename();//获取原文件名
            String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取文件后缀名
            //重新随机生成名字
            String filename = UUID.randomUUID().toString() +suffixName;
            File localFile = new File(uploadPath+"/"+filename);

            String path3 = System.getProperty("user.dir");
            log.info("path3:{}",path3);
            try {
                file.transferTo(localFile); //把上传的文件保存至本地
                Emergency emergency=this.getById(id);
                emergency.setAttachment(filename);
                this.updateById(emergency);
                return filename;//上传成功，返回保存的文件地址
            }catch (IOException e){
                log.info("上传失败{}",e);
                return "";
            }
        }else{
            log.info("文件为空");
            return "";
        }
    }
}
